package dfbz.com.controller.user;

import dfbz.com.constant.Constance;
import dfbz.com.controller.BaseServlet;
import dfbz.com.model.User;
import dfbz.com.model.UserFocus;
import dfbz.com.model.UserInfo;
import dfbz.com.service.impl.UserServiceImp;
import dfbz.com.utils.CheckStrUtil;
import dfbz.com.utils.PageUtil;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@WebServlet("/user/*")
public class UserServlet extends BaseServlet {

    UserServiceImp userService = new UserServiceImp();

    /**
     * 查找所有用户
     *
     * @param req
     * @param resp
     */
    public void showUser(HttpServletRequest req, HttpServletResponse resp) {

        List list = userService.showUser();

        //System.out.println("返回列表："+list);
        req.getSession().setAttribute("userList", list);
        try {
            req.getRequestDispatcher("/view/user").forward(req, resp);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * 分页查询用户
     *
     * @param req
     * @param resp
     */

    public void showUserByPage(HttpServletRequest req, HttpServletResponse resp) {

        try {
            req.setCharacterEncoding("UTF-8");
            String current = req.getParameter("current");
            String search = req.getParameter("search");
            if (current == null) {
                current = "1";
            }
            if (null != search) {
                System.out.println("搜索拿到的search：" + search);
                try {
                    String encode = URLEncoder.encode(search, "UTF-8");
                    System.out.println("编译后的search:" + encode);
                    resp.sendRedirect("/view/userPage?current=" + current + "&search=" + encode);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            } else {
                try {
                    resp.sendRedirect("/view/userPage?current=" + current);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }


    /**
     * 展示所点击用户的详细信息
     *
     * @param req
     * @param resp
     */
    public void showUserDetail(HttpServletRequest req, HttpServletResponse resp) {

        String userId = req.getParameter("uId");
//        System.out.println("得到的用户id为：" + userId);
//        不能直接用个List集合来取出对象数据的吧，当然报错了
//        UserInfo userInfoById = userService.findUserInfoById(Integer.parseInt(userId));

        try {
            resp.sendRedirect("/view/userDetail?uId="+userId);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    /**
     * 关注用户
     *
     * @param req
     * @param resp
     */
    public void follow(HttpServletRequest req, HttpServletResponse resp) {
        String uId = req.getParameter("uId");
        String userId = req.getSession().getAttribute("userId").toString();
        System.out.println("拿到uId：" + uId);
        System.out.println(userId);

        if (!userId.equals(uId)) {
            //先判断是否已经关注过
            UserFocus userFocus = userService.findFollowData(userId, uId);

            if (userFocus == null) {
                //这里才去加入关注表
                userService.addFollow(userId, uId);
            }
        }
        try {
            resp.getWriter().write("我拿到数据了：" + uId);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    public void unFollow(HttpServletRequest req, HttpServletResponse resp) {
        String uId = req.getParameter("uId");
//        注意了，req拿到的参数是String，session拿到的参数是Object
        Object userId = req.getSession().getAttribute("userId");

        if (!userId.toString().equals(uId)) {
            System.out.println("拿到了要取消关注的用户id：" + uId);
//          根据uId和userId删除关注列表
            userService.deleteFollow(userId, uId);
            try {
                resp.getWriter().write("要取消关注的id：" + uId);
            } catch (IOException e) {
                e.printStackTrace();
            }

        }

    }


    public void unFollowBut(HttpServletRequest req, HttpServletResponse resp) {
        String uId = req.getParameter("uId");
//        注意了，req拿到的参数是String，session拿到的参数是Object
        String current = req.getParameter("current");
        Object userId = req.getSession().getAttribute("userId");

        if (!userId.toString().equals(uId)) {
            try {
                userService.deleteFollow(userId, uId);
                resp.getWriter().write("要取消关注的id：" + uId);
                //req.setAttribute("current",current);
                myUser(req, resp);
            } catch (Exception e) {
                e.printStackTrace();
            }

        }

    }


    /**
     * 登录者所关注的用户列表
     *
     * @param req
     * @param resp
     */
    public void myUser(HttpServletRequest req, HttpServletResponse resp) {
        //查询关注表
        Object userId = req.getSession().getAttribute("userId");
        String current = req.getParameter("current");
        System.out.println("拿到的userid：" + userId);
        System.out.println("current：" + current);
        if (current == null) {
            current = "1";
        }
        List<UserFocus> userFocus = userService.findFocusUserPage(userId, Integer.parseInt(current));
        Long total = userService.findFocusTotalCount(userId);

        long totalPage = PageUtil.getTotalPage(total);
        req.getSession().setAttribute("myUserTotalPage", totalPage);
        ArrayList<User> list = new ArrayList<>();
        for (UserFocus focus : userFocus) {
            Integer userFocusId = focus.getUserFocusId();
            User user = userService.findUserById(userFocusId);
            list.add(user);
        }
        req.getSession().setAttribute("focusUser", list);
        try {
            resp.sendRedirect(req.getContextPath() + "/view/myUser");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    /**
     * 用户上传头像
     *
     * @param req
     * @param resp
     */
    public void uploadFile(HttpServletRequest req, HttpServletResponse resp) {

//        ServletFileUpload是什么东东
        try {
            ServletFileUpload sfu = new ServletFileUpload(new DiskFileItemFactory());
            sfu.setSizeMax(1024 * 1024 * 20L);

            List<FileItem> fileItems = sfu.parseRequest(req);
            FileItem fileItem = fileItems.get(0);
            String name = fileItem.getName();
            //String name = fileItems.get(0).getName();
            System.out.println(name);
            //重新组建文件名字，存到本地硬盘中
            String[] split = name.split("\\.");
            if (split.length == 2) {
                String fileName = CheckStrUtil.getUUID() + "." + split[1];
                String realPath = Constance.IMG_REAL_PATH + fileName;
                //如果文件不存在，就创建（写）该文件
                File file = new File(realPath);
                if (!file.exists()) {
//                    用fileItem来写
                    fileItem.write(file);
                }

//                把新的路径存到数据库中；存的网页资源路径
                String path = req.getContextPath() + Constance.IMG_CONTEXT_PATH + fileName;
                Object userId = req.getSession().getAttribute("userId");
                userService.updateImg(path, userId.toString());

//                在这里去更新用户的详细信息
                Map userDetailInfo = userService.findUserDetailInfo(userId.toString());
                req.getSession().setAttribute("myDetail", userDetailInfo);


                resp.getWriter().write(path);
            } else {
                resp.getWriter().write("fail");
            }


        } catch (Exception e) {
            e.printStackTrace();
        }


    }

    /**
     * 用户（user_look）更新自己的详细信息
     *
     * @param req
     * @param resp
     */
    public void updateUser(HttpServletRequest req, HttpServletResponse resp) {

        try {
            req.setCharacterEncoding("utf-8");

            String userId = req.getSession().getAttribute("userId").toString();
            String realName = req.getParameter("realName");
            String dept = req.getParameter("dept");
            String phone = req.getParameter("phone");
            String age = req.getParameter("age");
//        sex :0是男，1是女
            String sex = req.getParameter("sex");
//        isSecret 1是保密，0是公开（1或null）
            String isSecret = req.getParameter("isSecret");

//        点击保存后更新用户信息（user_info表的）
            UserInfo userInfo = new UserInfo();
            userInfo.setPhone(phone);
            userInfo.setGender(sex);
            userInfo.setRealName(realName);
            if (null != age && !"".equals(age)) {
                userInfo.setAge(Integer.parseInt(age));

            }
//            问题：设置了describe就会报错？
//            userInfo.setDescribe("不能设置，我也没办法");
            userInfo.setUserId(Integer.parseInt(userId));
            System.out.println(userInfo);
            userService.updateTable(userInfo);


//        user表的
            User user = new User();
//            System.out.println("-----------");
//            System.out.println("拿到是否私密："+isSecret);
            if (isSecret == null) {
                user.setIsSecret("0");
            } else {
                user.setIsSecret("1");
            }
//        找到对应部门id
            System.out.println("部门的名称：" + dept);
            Integer id = userService.findDeptIdByDeptName(dept);
            System.out.println("找到的部门id：" + id);
            user.setDeptId(id);
            user.setId(Integer.parseInt(userId));
            System.out.println(user);
            userService.updateTable(user);


//                在这里去更新用户的详细信息
            Map userDetailInfo = userService.findUserDetailInfo(userId.toString());
            req.getSession().setAttribute("myDetail", userDetailInfo);

            //        保存后跳回主页
            resp.sendRedirect("/view/home");
        } catch (Exception e) {
            e.printStackTrace();
        }


    }
}
